<template>
  <el-dialog
    v-model="dialogVisible"
    title="试卷评分"
    width="60%"
    :before-close="handleClose"
    class="grading-dialog"
  >
    <div class="grading-content">
      <div class="student-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学号">
            {{ submission ? submission.student_id : '' }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ submission ? submission.student_name : '' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(submission ? submission.status : '')">
              {{ getStatusText(submission ? submission.status : '') }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div v-if="hasAttachments" class="submission-attachments">
        <h4>试卷扫描件：</h4>
        <el-card shadow="never" class="attachment-list">
          <div v-for="attachment in submission.attachments" :key="attachment.id" class="attachment-item">
            <el-link
              :href="attachment.file_path"
              target="_blank"
              type="primary"
            >
              <i class="el-icon-document"></i>
              {{ getFileName(attachment.file_path) }}
            </el-link>
          </div>
        </el-card>
      </div>

      <el-form
        :model="gradingForm"
        ref="formRef"
        label-width="100px"
        class="grading-form"
      >
        <el-form-item
          label="分数"
          prop="score"
          :rules="scoreRules"
        >
          <el-input-number
            v-model="gradingForm.score"
            :min="0"
            :max="100"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="评语" prop="feedback">
          <el-input
            v-model="gradingForm.feedback"
            type="textarea"
            :rows="4"
            placeholder="请输入评语（选填）"
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="submitGrade"
          :loading="submitting"
          :disabled="!gradingForm.score"
        >
          提交评分
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  submission: {
    type: Object,
    default: () => null
  }
})

const emit = defineEmits(['update:visible', 'graded'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const gradingForm = ref({
  score: null,
  feedback: ''
})

const submitting = ref(false)
const formRef = ref(null)

// 计算属性
const hasAttachments = computed(() => {
  return props.submission &&
         props.submission.attachments &&
         props.submission.attachments.length > 0
})

const submissionId = computed(() => {
  return props.submission ? props.submission.submission_id : null
})

// 表单验证规则
const scoreRules = [
  { required: true, message: '请输入分数', trigger: 'blur' },
  { type: 'number', min: 0, max: 100, message: '分数必须在0-100之间', trigger: 'blur' }
]

const getStatusType = (status) => {
  const types = {
    'SUBMITTED': 'success',
    'NOT_SUBMITTED': 'warning',
    'GRADED': 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    'SUBMITTED': '已提交',
    'NOT_SUBMITTED': '未提交',
    'GRADED': '已评分'
  }
  return texts[status] || '未知状态'
}

const getFileName = (path) => {
  if (!path) return ''
  return path.split('/').pop()
}

const submitGrade = async () => {
  if (!gradingForm.value.score) {
    ElMessage.warning('请输入分数')
    return
  }

  if (!submissionId.value) {
    ElMessage.error('无效的提交记录')
    return
  }

  submitting.value = true
  try {
    await axios.post(
      `/backend/api/exam/submission/${submissionId.value}/grade/`,
      {
        grade: gradingForm.value.score,
        feedback: gradingForm.value.feedback
      },
      {
        withCredentials: true
      }
    )

    ElMessage.success('评分提交成功')
    emit('graded')
    handleClose()
  } catch (error) {
    console.error('评分提交失败:', error)
    ElMessage.error('评分提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  gradingForm.value = {
    score: null,
    feedback: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
  emit('update:visible', false)
}
</script>

<style scoped>
.grading-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.grading-content {
  padding: 20px;
}

.student-info {
  margin-bottom: 20px;
}

.submission-attachments {
  margin: 20px 0;
}

.attachment-list {
  background-color: #f8f9fa;
}

.attachment-item {
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
}

.attachment-item:last-child {
  border-bottom: none;
}

.grading-form {
  margin-top: 20px;
}
</style>